package com.devunion.bogdan.view.project.actions;

import com.devunion.bogdan.view.wizards.NewProjectWizard;
import com.devunion.bogdan.model.project.*;
import com.devunion.bogdan.model.project.info.ProjectInfo;
import com.devunion.bogdan.model.project.dao.ProjectDao;
import com.devunion.bogdan.model.UserManager;
import com.devunion.bogdan.util.IconHelper;
import com.devunion.bogdan.spring.Context;

import java.awt.event.ActionEvent;
import java.util.Map;
import java.util.List;

import org.apache.log4j.Logger;

import javax.swing.*;

class NewProjectAction extends AbstractAction {
    private static Logger log = Logger.getLogger(NewProjectAction.class);

    private NewProjectWizard wizzard = new NewProjectWizard();
    private ProjectDao projectDao;

    public NewProjectAction() {
        super(null, IconHelper.getIcon("CreateNewProject16.gif"));
        putValue(Action.LARGE_ICON_KEY, IconHelper.getIcon("CreateNewProject48.gif"));

        projectDao = (ProjectDao) Context.getContext().getBean("projectDao");
    }

    public void actionPerformed(ActionEvent e) {

        List<ProjectInfo> projectInfos = projectDao.loadProjectInfos();

        wizzard.setProjectInfos(projectInfos);

        Map result = wizzard.show();

        if (result == null) {
            return;
        }

        String projectName = (String) result.get(NewProjectWizard.PROJECT_NAME);

        // trick to solve the problem with creation of projects with the same name.
        if (projectName == null) {
            projectName = NewProjectWizard.DEFAULT_PROJECT_NAME;
        }

        try {

            Project newProject = ProjectManager.getInstance().createNewProject(projectName);
            newProject.setOwner(UserManager.getInstance().getUser());

            ProjectManager.getInstance().loadProject(newProject);
            ProjectManager.getInstance().saveCurrentProject();
        } catch (ProjectCreationException e1) {
            log.error(e1.getMessage(), e1);
        } catch (ProjectSavingException e1) {
            log.error(e1.getMessage(), e1);
        } catch (ProjectLoadingException e1) {
            log.error(e1.getMessage(), e1);
        }
    }
}
